package com.liuyang.filter;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import com.google.code.kaptcha.Constants;
import com.liuyang.entity.Account;
import com.liuyang.entity.Logs;
import com.liuyang.service.LogsService;
import com.liuyang.utils.ApplicationContextUtils;
import com.liuyang.utils.MapCacheManagerUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

public class AdminInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("account");
        if(ObjectUtil.isNull(account)) {
            String contextPath = request.getServletContext().getContextPath();
            response.sendRedirect(contextPath + "/logout");
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String uri = request.getRequestURI();
        String logIp = request.getRemoteAddr();
        LogsService logsService = (LogsService) ApplicationContextUtils.getBean("logsServiceImpl");
        Map interfaceInfoMap = MapCacheManagerUtils.getInstance().getMapCache();
        String userAccount = MapCacheManagerUtils.getInstance().getUserAccount();
        if(interfaceInfoMap.containsKey(uri)) {
            String logInfo = interfaceInfoMap.get(uri).toString();
            String logTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            // Map map = MapBuilder.create().put("logInfo", logInfo).put("logIp", logIp).put("logTime", logTime).put("logAccountName", userAccount).map();
            // logsService.addLogsInfo(map);
            Snowflake snowflake = new Snowflake(2,3);
            String id = snowflake.nextIdStr();
            Logs logs = new Logs();
            logs.setLogInfo(logInfo);
            logs.setLogTime(logTime);
            logs.setLogIp(logIp);
            logs.setLogAccountName(userAccount);
            logs.setId(id);
            logsService.save(logs);
        }
    }
}
